package com.tyut.homework.controller;

import ch.qos.logback.core.OutputStreamAppender;
import com.tyut.homework.pojo.Admin;
import com.tyut.homework.pojo.Backups;
import com.tyut.homework.pojo.Student;
import com.tyut.homework.repository.AdminRepository;
import com.tyut.homework.repository.BackupsRepository;
import com.tyut.homework.response.ServerResponse;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.tomcat.jni.Time;
import org.apache.tomcat.util.http.fileupload.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.web.bind.annotation.*;
import sun.nio.ch.IOUtil;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.nio.charset.StandardCharsets;
import java.sql.Date;
import java.util.Objects;
import java.util.UUID;

@Api("登录管理")
@RestController
public class UserController {

    @Autowired
    private AdminRepository adminRepository;

    @Autowired
    private BackupsRepository backupsRepository;

    @GetMapping("/admin/getPasswd/{username}")
    public ServerResponse getPasswd(@PathVariable String username){
        Admin byUsername = adminRepository.findByUsername(username);
        if (byUsername == null){
            return ServerResponse.createByError();
        }
        return ServerResponse.createBySuccess(byUsername);
    }

    @GetMapping("/admin/findAll/{start}/{end}")
    public ServerResponse findAll(@PathVariable Integer start,
                                  @PathVariable Integer end){
        Sort sort = new Sort(Sort.Direction.ASC,"id");
        Pageable pageable = new PageRequest(start, end, sort);
        Page<Admin> all = adminRepository.findAll(pageable);
        return ServerResponse.createBySuccess(all);
    }

    @ApiOperation("查询信息")
    @GetMapping("/admin/findById/{id}")
    public ServerResponse findById(@PathVariable Integer id){
        Admin admin = adminRepository.findById(id).get();
        return ServerResponse.createBySuccess(admin);
    }


    @ApiOperation("添加")
    @PostMapping("/admin/add")
    public ServerResponse add(Admin admin){
        return ServerResponse.createBySuccess("添加成功",adminRepository.save(admin));
    }

    @ApiOperation("更新信息")
    @PostMapping("/admin/update")
    public ServerResponse update(Admin admin){
        System.out.println(admin.toString());
        return  ServerResponse.createBySuccess(adminRepository.saveAndFlush(admin));
    }

    @ApiOperation("删除")
    @GetMapping("/admin/delete/{id}")
    public ServerResponse delete(@PathVariable Integer id){
        adminRepository.deleteById(id);
        return ServerResponse.createBySuccess("删除成功!");
    }

    @GetMapping("/admin/findBackups/{start}/{end}")
    public ServerResponse findBackups(@PathVariable Integer start,
                                      @PathVariable Integer end){
        Sort sort = new Sort(Sort.Direction.ASC,"id");
        Pageable pageable = new PageRequest(start, end, sort);
        Page<Backups> all = backupsRepository.findAll(pageable);
        return ServerResponse.createBySuccess(all);
    }

    @GetMapping("/admin/addBackups")
    public ServerResponse addBackups(HttpServletResponse response){
        final  String username = "root";
        final String password = "root";
        String fileName = UUID.randomUUID().toString().replaceAll("-", "")+".dump";
        String path = "/home/fantj/";
        File file = new File(path,fileName);
        String exec = "mysqldump  --user=root --password=root --opt stu_apt_sys>"+file.toString();
        System.out.println(exec);
        try {
            Runtime.getRuntime().exec(new String[]{"sh", "-c", exec});
        } catch (IOException e) {
            e.printStackTrace();
        }
        try (
                //jdk7新特性，可以直接写到try()括号里面，java会自动关闭
                InputStream inputStream = new FileInputStream(file);
                OutputStream outputStream = response.getOutputStream()
        ) {
            Thread.sleep(3000);
            System.out.println("开始下载");
            //指明为下载
            response.setContentType("application/x-download");
            response.addHeader("Content-Disposition", "attachment;fileName=" + fileName);   // 设置文件名
            //把输入流copy到输出流
            IOUtils.copy(inputStream, outputStream);
            outputStream.flush();

        } catch (IOException | InterruptedException e) {
            e.printStackTrace();
        }
//        try {
//            process = Runtime.getRuntime().exec(new String[]{"sh","-c",exec});
//            Thread.sleep(3000);
//            os = response.getOutputStream();
//            bis = new BufferedInputStream(new FileInputStream(file));
//            if (file.exists()) {
//                System.out.println(file+"文件存在");
//                response.reset();
//                response.setHeader("Content-Disposition", "attachment;filename="+fileName);
////                response.setHeader("Content-Length", String.valueOf(file.length()));
//                response.setHeader("Connection", "close");
//                response.setHeader("Content-Type", "application/octet-stream");
//                byte[] buffer = new byte[1024];
//                int i = bis.read(buffer,0,1024);
//                while (i != -1) {
//                    os.write(buffer, 0, i);
//                }
//                bis.close();
//                os.close();
//            } else {
//                System.out.println(file+"文件不存在");
//            }
//        } catch (InterruptedException | IOException e1) {
//            e1.printStackTrace();
//        } finally {
//            try {
//                if (os != null) {
//                    os.close();
//                }
//            } catch (IOException e) {
//                e.printStackTrace();
//            }
//        }
        // 添加至数据库
        Backups backups = new Backups();
        backups.setName(file.toString());
        System.out.println(backups.toString());
        backupsRepository.save(backups);
        return ServerResponse.createBySuccess();
    }

}
